using System;
using System.ComponentModel.Composition;
using System.Linq;
using System.Windows;
using Caliburn.Micro;
using Client.Common;
using Client.Messages;
using Dto.ApiRequests;
using Sanelib.Common.SystemSettings;
using Sanelib.Core;
using Sanelib.Core.Utility;
using Sanelib.Dto;
using Sanelib.Net.Http;
using Sanelib.Services.Impl;

namespace ClientUI.ViewModel
{
    [Export(typeof(IShell))]
    public class ShellViewModel : Conductor<object>, IShell, IHandle<ChangeView>
    {
        private readonly object[] _views;

        public ShellViewModel()
        {
            Logger.Log(LogType.Info, this, "Starting Tracker");

            var clientConfig = ConfigProvider.GetClientConfig();
            if (string.IsNullOrEmpty(clientConfig.ServiceUrl))
            {
                clientConfig = new ClientConfig
                {
                    ServiceUrl = "http://localhost:9095/",
                    FromAgency = "SSSPL",
                    ToAgency = "SSPL",
                    FromSystem = "SSPL",
                    ToSystem = "SSPL",
                    MachineName = "SSPL",
                    SessionTime = 8,
                    UsePrint = true
                };
                ConfigProvider.SetClientConfig(clientConfig, true);
            }

            EventAggregatorContainer.EventAggregator.Subscribe(this);

           _views = new object[]
                        {
                            new CardRegViewModel(),
                            new TrackerViewModel()
                        };

           Handle(new ChangeView("CardRegViewModel")); 
        }

        public void Handle(ChangeView message)
        {
            var view = _views.FirstOrDefault(v => v.GetType().Name.Equals(message.ViewName));
            
			if(view == null)
			{
				MessageBox.Show(string.Format("{0} View not found", message));
				return;
			}

			ActivateItem(view);
        }

        protected override void OnActivate()
        {
            base.OnActivate();
			Logger.Log(LogType.Info, this, "Activating Tracker");

            var login = new LoginForm
            {
                Username = "admin",
                Password = "admin"
            };

            ErrorResult errors;

            var response = Processor.ExecuteRequest<LoginForm, WebApiResonseBase>(ContentType.JSON, RequestType.POST, login, out errors);

            if (!errors.IsValid)
            {
                throw new Exception(errors.ToXml()); 
            }

            Logger.Log(LogType.Info, this, response.ToString());
        }

        protected override void OnDeactivate(bool close)
        {
            base.OnDeactivate(close);
            Logger.Log(LogType.Info, this, "Deactivating Tracker");
        }
    }
}
